/**  
 * @Title: JpushInterface.java
 * @Package cn.jpush.api.examples
 * @date 2015年9月25日 上午9:29:16
 * @version V1.0  
 */
package com.zx.cloud.common.jpush;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.github.pagehelper.util.StringUtil;
import com.zx.cloud.config.ConfigUtil;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;

/**
 * 该类的功能用途 项目名称: [zzzs]<br/>
 * 类名称: [JpushInterface]<br/>
 * 创建人: [GaoNan]<br/>
 * 创建时间: [2015年9月25日 上午9:29:16]<br/>
 * 修改人: [GaoNan]<br/>
 * 修改时间: [2015年9月25日 上午9:29:16]<br/>
 * 修改备注: [说明本次修改内容]<br/>
 * 版本: [v1.0]<br/>
 */
@Component
public class JpushInterface {

	private static Logger LOG = Logger.getLogger(JpushInterface.class);

	private volatile static JPushClient jpushClient;

	@Autowired
	private ConfigUtil configUtil;

	public JPushClient getJPushClient() {
		if (jpushClient == null) {
			synchronized (JpushInterface.class) {
				if (jpushClient == null) {
					jpushClient = new JPushClient(configUtil.getJpushMasterSecret(), configUtil.getJpushAppKey());
				}
			}
		}
		return jpushClient;
	}

	public static PushPayload buildPushMessage(String alias, String content, Map<String, Object> params) {
		Message.Builder b = Message.newBuilder().setMsgContent(content);
		if (params != null) {
			for (String key : params.keySet()) {
				if(StringUtil.isEmpty(key)||params.get(key)==null){
					
				}else{
					b.addExtra(key, params.get(key).toString());
				}
			}
		}
		return PushPayload.newBuilder().setPlatform(Platform.android_ios()).setOptions(Options.newBuilder().setApnsProduction(false).build()).setAudience(Audience.alias(alias)).setMessage(b.build()).build();
	}

	private static PushPayload buildAliasPushMessage(List<String> alias, String content, Map<String, Object> params) {
		Message.Builder b = Message.newBuilder().setMsgContent(content);
		if (params != null) {
			for (String key : params.keySet()) {
				if(StringUtil.isEmpty(key)||params.get(key)==null){
					
				}else{
					b.addExtra(key, params.get(key).toString());
				}
			}
		}
		 return PushPayload.newBuilder()
	                .setPlatform(Platform.android_ios())
	                .setAudience(Audience.newBuilder()
	                        .addAudienceTarget(AudienceTarget.alias(alias))
	                        .build())
	                .setMessage(b.build())
	                .build();
//		return PushPayload.newBuilder().setPlatform(Platform.android_ios()).setOptions(Options.newBuilder().setApnsProduction(true).build()).setAudience(Audience.alias(alias)).setMessage(b.build()).build();
	}

	public PushResult sendAllClientsPushMessage(List<String> registrationIds,String content, Map<String, Object> params) {
		try {
			PushResult result = getJPushClient().sendPush(buildAliasPushMessage(registrationIds, content, params));
			LOG.info("Got result - " + result);
			return result;
		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
		}
		return null;
	}
	
	/************************************************************************************/
	public  PushResult sendPushMessage(String alias, String content, Map<String, Object> params) {
		PushResult result = null;
		try {
			result = getJPushClient().sendPush(buildPushMessage(alias, content, params));
			LOG.info("Got result - " + result);
		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
		}
		return result;
	}

	/**
	 * @param content
	 *            发送的消息体, 提醒内容
	 * @param alias
	 *            用户ID userId
	 */
	public PushResult sendPushForAlert(String content, String title, String alias) {
		PushResult result = null;
		try {
			result = getJPushClient().sendPush(
					PushPayload.newBuilder().setPlatform(Platform.android_ios()).setAudience(Audience.alias(alias)).setNotification(Notification.android(content, title, null)).build());
			LOG.info("Got result - " + result);
		} catch (APIConnectionException e) {
			LOG.error("Connection error. Should retry later. ", e);
		} catch (APIRequestException e) {
			LOG.error("Error response from JPush server. Should review and fix it. ", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			LOG.info("Msg ID: " + e.getMsgId());
		}
		return result;
	}

}
